﻿using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Media;
using System.Windows;
using PdfiumViewer;
using System.Drawing.Printing;
using System.Collections.Generic;
using System;

namespace MT.CustomUserControl
{
    /// <summary>
    /// 工具箱
    /// </summary>
    public class ToolBoxHelper
    {
        /// <summary>
        /// listbox值提取
        /// </summary>
        /// <param name="_box"></param>
        /// <param name="other"></param>
        /// <returns></returns>
        public static string ListToString(List<string> strings, string other)
        {
            string result = "";

            foreach (var item in strings)
            {
                if (item == "其他" && other != "")
                    result += other + ",";
                else
                    result += item + ",";
            }

            result = result.TrimEnd(',');

            return result;
        }

        /// <summary>
        /// 获取随机种子
        /// </summary>
        /// <returns></returns>
        public static int GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }

        #region 文件夹操作

        public static void CopyDirectory(string srcDir, string destDir)
        {
            if (Directory.Exists(destDir))//若目标文件夹不存在
            {
                //再遍历文件夹
                string[] dirs = Directory.GetDirectories(srcDir);
                foreach (string path in dirs)
                {
                    DirectoryInfo directory = new DirectoryInfo(path);
                    string newDir = Path.Combine(destDir, directory.Name);
                    if (Directory.Exists(newDir))
                        Directory.Delete(newDir, true);

                    Directory.CreateDirectory(newDir);
                    CopyDirectory(path, newDir);
                }

                //先遍历文件 ，有则复制
                FileInfo fileInfo;
                string[] files = Directory.GetFiles(srcDir);
                foreach (string path in files)
                {
                    fileInfo = new FileInfo(path);
                    string newPath = Path.Combine(destDir, fileInfo.Name);
                    File.Copy(path, newPath, true);
                }

            }
        }

        #endregion

        #region 手机号，身份证号脱敏处理


        /// <summary>
        /// 隐藏敏感信息
        /// </summary>
        /// <param name="info">信息实体</param>
        /// <param name="left">左边保留的字符数</param>
        /// <param name="right">右边保留的字符数</param>
        /// <param name="basedOnLeft">当长度异常时，是否显示左边 </param>
        /// <returns></returns>
        public static string HideSensitiveInfo(string info, int left, int right, bool basedOnLeft = true)
        {
            if (String.IsNullOrEmpty(info))
            {
                return "";
            }
            StringBuilder sbText = new StringBuilder();
            int hiddenCharCount = info.Length - left - right;
            if (hiddenCharCount > 0)
            {
                string prefix = info.Substring(0, left), suffix = info.Substring(info.Length - right);
                sbText.Append(prefix);
                for (int i = 0; i < hiddenCharCount; i++)
                {
                    sbText.Append("*");
                }
                sbText.Append(suffix);
            }
            else
            {
                if (basedOnLeft)
                {
                    if (info.Length > left && left > 0)
                    {
                        sbText.Append(info.Substring(0, left) + "****");
                    }
                    else
                    {
                        sbText.Append(info.Substring(0, 1) + "****");
                    }
                }
                else
                {
                    if (info.Length > right && right > 0)
                    {
                        sbText.Append("****" + info.Substring(info.Length - right));
                    }
                    else
                    {
                        sbText.Append("****" + info.Substring(info.Length - 1));
                    }
                }
            }
            return sbText.ToString();
        }


        #endregion

        #region 打印


        /// <summary>
        /// 调用打印机打印,此方法如果目标电脑上未安装pdf阅读软件，会提示打印出错
        /// </summary>
        /// <param name="PDFPath">PDF文件路径</param>
        /// <param name="PrinterName">打印机名称</param>
        public static void PrintFile(string PDFPath, string PrinterName)
        {
            try
            {
                PrintDocument pd = new PrintDocument();
                Process p = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.CreateNoWindow = true;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                startInfo.UseShellExecute = true;
                startInfo.FileName = PDFPath;
                startInfo.Verb = "print";
                startInfo.Arguments = @"/p /h \" + PDFPath + "\"\"" + PrinterName + "\"";
                p.StartInfo = startInfo;
                p.Start();
                p.WaitForExit();
            }
            catch (Exception ex)
            {
                MessageBox.Show("打印出错，\r\n请检查PDF文件默认打开方式是否争取！");
            }
        }

        /// <summary>
        /// 此方法可以在不安装pdf阅读器的电脑上打印
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="PrinterName">Name of the printer.</param>
        /// <returns></returns>
        public static bool PrintPDF(string path, string PrinterName)
        {
            try
            {
                using (var document = PdfDocument.Load(path))
                {
                    using (var printDocument = document.CreatePrintDocument())
                    {
                        string fileName = Path.GetFileNameWithoutExtension(path);
                        printDocument.PrinterSettings.PrintFileName = path;
                        printDocument.PrinterSettings.PrinterName = PrinterName;
                        printDocument.DocumentName = fileName;
                        printDocument.PrintController = new StandardPrintController();
                        printDocument.Print();

                        return true;
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show($"Print error，\r\n{ex}！");
                return false;
            }

        }


        #endregion

        #region UI

        /// <summary>
        /// 获取视觉树上指定名称的控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parent"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public static T GetVisualChild<T>(DependencyObject parent, Func<T, bool> predicate) where T : Visual
        {
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                DependencyObject v = (DependencyObject)VisualTreeHelper.GetChild(parent, i);
                T child = v as T;
                if (child == null)
                {
                    child = GetVisualChild<T>(v, predicate);
                    if (child != null)
                    {
                        return child;
                    }
                }
                else
                {
                    if (predicate(child))
                    {
                        return child;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 在视觉树上找到指定类型的控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            if (obj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                    if (child != null && child is T)
                    {
                        return (T)child;
                    }
                    T childItem = FindVisualChild<T>(child);
                    if (childItem != null) return childItem;
                }
            }
            return null;
        }

        /// <summary>
        /// 查找控件中的所有指定子项
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static List<T> FindAllVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            if (obj != null)
            {
                List<T> list = new List<T>();
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                    if (child != null && child is T)
                    {
                        list.Add((T)child);
                    }

                    List<T> list_sub = FindAllVisualChild<T>(child);
                    if (list_sub != null && list_sub.Count > 0)
                    {
                        foreach (var item in list_sub)
                        {
                            list.Add(item);
                        }
                    }
                }

                return list;
            }
            return null;
        }

        #endregion

        #region 其他

        /// <summary>
        /// 进行显示首字母大小写
        /// </summary>
        /// <param name="CnStr"></param>
        /// <returns></returns>
        public static string GetFirstCode(string CnStr)
        {
            string strTemp = "";
            int iLen = CnStr.Length;
            //获取到字符串的长度
            //通过循环，一次得到每个汉字的拼音首字母缩写
            for (int i = 0; i <= iLen - 1; i++)
            {
                //拼接返回结果
                strTemp += GetSpellCode(CnStr.Substring(i, 1));
            }
            return strTemp;
        }

        /// <summary>
        /// 拼音转化类型方法
        /// </summary>
        /// <param name="CnChar">字符</param>
        /// <returns></returns>
        private static string GetSpellCode(string CnChar)
        {
            long iCnChar;
            byte[] arrCN = System.Text.Encoding.Default.GetBytes(CnChar);
            //将传进来的参数转换为byte格式的，如果是英文字母，它的长度应该为1
            //如果是中文，那它的长度应该是2	
            //如果是字母，则直接返回
            if (arrCN.Length == 1)
            {
                CnChar = CnChar.ToUpper();
            }
            else
            {
                //是中文的话，长度就为2，分别接收到它的两个字节码
                int area = (short)arrCN[0];
                int pos = (short)arrCN[1];
                //【<<】是位运算符，向左移动8位
                iCnChar = (area << 8) + pos;
                //声明字母字符串已经对应位置的区间数组
                string letter = "ABCDEFGHJKLMNOPQRSTWXYZ";
                int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614,
                    48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906,
                    51387, 51446, 52218, 52698, 52980, 53689, 54481, 55290 };
                for (int i = 0; i < 23; i++)
                {
                    //通过循环对比得到区间的位置，然后提取出相应位置的字母
                    if (areacode[i] <= iCnChar && iCnChar < areacode[i + 1])
                    {
                        CnChar = letter.Substring(i, 1);
                        break;
                    }
                    else
                    {
                        //如果无法识别（不在区间内，比如说￥、%、&等特殊符号）
                        //就将它统一归类为【#】
                        CnChar = "#";
                    }
                }
            }
            return CnChar;
        }

        #endregion
    }
}
